import HttpUtils from '../HttpUtils/HttpUtils';
// 获取当前时间戳
var timestamp = Date.parse(new Date()) / 1000;
var T;
Page({
	...HttpUtils.func,
	data: {
		scorePop: false,
		examId: '',
		paperId: '',
		timeLimit: '',
		topicNum: '',
		//任务列表
		examList: [],
		examPaper: [],
		examCheck: '',

		content: [],
		endTime: '',
		aa: false,
		bb: false,
		choiceIndex: '',
		//正确错误统计
		right: 0,
		wrong: 0,
		examIndex: 0,
		nextOk: true,
		submitOk: false,
		Detail: false,
		choiceArr: [],
		detailArr: [],
		flag: false,
		//判断单选还是多选
		type: '',
		userChoice: [],
		//上一次
		lastPaperIndex: '',
		isChecked: false,
		again: "", //判断是否重新答题
	},
	/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
	onReady: function() {
	},

	onLoad(params) {
		var again = params.again;
		var examId = params.examId;
		var timeLimit = params.timeLimit;
		this.setData({
			examId: examId,
			timeLimit: timeLimit,
			again: again,
		})
		//考试答题接口
		this.loadExamPaper();
		//倒计时
		this.goEndTime();
	},
	onUnload() {
		clearInterval(T);	//停止定时
	},
	//倒计时
	goEndTime: function() {
		this.setData({
			endTime: new Date().getTime() + this.data.timeLimit * 60 * 1000,
		})
		//倒计时
		let getTime = () => {
			let stopDate = +this.data.endTime;//获取截至时间戳(.getTime()==+)
			let nowDate = +new Date()//获取当前时间戳
			let dTime = stopDate - nowDate;//计算时间差
			let s = dTime / 1000;//计算秒
			let m = s / 60;//计算分钟
			let h = m / 60;//计算小时
			let day = h / 24;//计算天

			if (s >= 0) {
				this.setData({
					day: parseInt(day),
					h: parseInt(h % 24),
					m: parseInt(m % 60),
					s: parseInt(s % 60),
				})
			} else {
				clearInterval(T);	//停止定时
				wx.alert({
					content: '答题已结束',
					success: () => {
						wx.navigateBack({
							delta: 1
						})
					}
				});
			}
		}
		getTime()//开始定时
		T = setInterval(() => {
			getTime()
		}, 1000)
	},

	//考试答题接口
	loadExamPaper: function() {
		var newUrl = getApp().globalData.dangjianUrl + "/exam/examPaper";
		var params = {};
		params["examId"] = this.data.examId + "";
		params = JSON.stringify(params);
		this.httpGet(newUrl, params, "查询考试答题接口调用失败").then(
			(respData) => {
				console.log(respData)
				var result = respData.data.result.code;
				if (respData.data.code != 4) {
					if (1 == result) {
						var paper = respData.data.paper;
						var paperId = paper.paperId;		//试卷ID
						var timeLimit = paper.timeLimit; //考试时限，单位分钟
						var topicNum = paper.topicNum;		//总题数 
						this.setData({
							examList: respData.data.questions,
						})
						var questions = this.data.examList[0];		//试卷题目集对象
						console.log(questions)
						var obj = questions.content[0];
						var arr = []
						var brr = []
						for (let i in obj) {
							arr.push(obj[i]); //属性
							brr.push(i);
						}
						console.log(arr)
						console.log(brr)
						this.setData({
							"examPaper": questions,
							"content": arr,
							"brr": brr,
							"topicNum": topicNum,
							"paperId": paperId,
							"timeLimit": timeLimit,
							"userChoice": [],
						});
					} else {
            this.showPageMsg("alert", respData.data.result.description)
					}
				} else {
					wx.alert({
						title: respData.data.msg,
						success: () => {
							wx.navigateBack({
								delta: 1
							})
						}
					});
				}
			}
		);
	},

	//删除方法
	remove: function(array, val) {
		for (var i = 0; i < array.length; i++) {
			if (array[i] == val) {
				array.splice(i, 1);
			}
		}
		return -1;
	},
	//选择
	changeChoice: function(event) {
		var type = event.currentTarget.dataset.type;
		var choices = event.currentTarget.dataset.choices + "";		//上次选中的下标
		var choice = event.currentTarget.dataset.choice;					//客户选项 ABCD
		var choiceIndex = event.currentTarget.dataset.index + "";	//客户选项下标 	
		var paperIndex = event.currentTarget.dataset.paperIndex + "";	  //题目题号
		var lastPaperIndex = event.currentTarget.dataset.lastPaperIndex + "";//上次题目题号 

		//选中的下标
		if ((type == 'radio' || type == 'judge') && !this.data.Detail) {
			if (lastPaperIndex == paperIndex && choices == choiceIndex) {
				choiceIndex = -1;
			}
			this.setData({
				type: type,
				aa: true,
				choiceIndex: choiceIndex,
			})
		} else if (type == 'check') {
			if (lastPaperIndex == paperIndex && choices.indexOf(choiceIndex) == -1) {
				choiceIndex = choiceIndex + choices;
			} else {
				if (lastPaperIndex == paperIndex) {
					choiceIndex = choices.replace(choiceIndex, "");
				}
			}
			if (this.data.userChoice.indexOf(choice) == -1) {
				this.data.userChoice.push(choice);	//添加
			} else {
				this.remove(this.data.userChoice, choice);
			}
			this.setData({
				type: type,
				aa: false,
				choiceIndex: choiceIndex,
				userChoice: this.data.userChoice
			})
		}
		//判读是否选择 多选 单选
		if (type == 'check') {
			if (choiceIndex == '') {
				this.setData({
					isChecked: false,
				})
			} else {
				this.setData({
					isChecked: true,
				})
			}
		} else {
			if (choiceIndex != -1) {
				this.setData({
					isChecked: true,
				})
			} else {
				this.setData({
					isChecked: false,
				})
			}
		}
		this.setData({
			lastPaperIndex: paperIndex,
		})

	},
	//下一题
	nextExam: function(event) {
		var choice = event.currentTarget.dataset.choice;	//客户答案
		var type = event.currentTarget.dataset.type; 		//题型 单选多选
		var Detail = event.currentTarget.dataset.detail; //是否已经显示解题详情
    var topicNum = event.currentTarget.dataset.topicnum; //总题数
		var index = event.currentTarget.dataset.index;			//客户选题目编号
		var answer = event.currentTarget.dataset.answer;	//正确答案
    var detailId = event.currentTarget.dataset.detailid;	//试卷问题ID、
		//判断是否选择-----------------------------------------
		if (this.data.isChecked || Detail) {
		} else {
			return this.showPageMsg("tips", "请选择答案！")
		}
		this.setData({
			isChecked: false,
		})
		// this.data.choiceIndex;
		// if (choice == undefined && this.data.userChoice == '') {
		// 	return this.showPageMsg("tips", "请选择答案！")
		// }
		//拼接试卷ID------------------------------------------
		var detailArr = [];
		detailArr.push(detailId);
		var olddetailArr = this.data.detailArr;
		if (olddetailArr.length != 0 && Detail == false) {
			detailArr = olddetailArr.concat(detailArr)
			this.setData({
				detailArr: detailArr,
			})
		}
		if (olddetailArr.length == 0) {
			this.setData({
				detailArr: detailArr,
			})
		}
		// 拼接答案---------------------------------------
		var choiceArr = [];
		//多选
		if (type == 'check') {
			choice = choice.sort().join(',');
		}
		choiceArr.push(choice);
		var olddetailArr = this.data.choiceArr;
		if (olddetailArr.length != 0 && Detail == false) {
			choiceArr = olddetailArr.concat(choiceArr)
			this.setData({
				choiceArr: choiceArr,
			})
		}
		if (olddetailArr.length == 0) {
			this.setData({
				choiceArr: choiceArr,
			})
		}
		console.log('detailArr:' + detailArr);
		console.log('choiceArr:' + choiceArr);
		//如果正确直接下一题，right+1
		if (index < topicNum) {  							//当前题数大于总题数 显示提交
			if (choice == answer || Detail) {   //当前题数小于总题数 判断
				if (choice == answer) {
					this.setData({
						right: this.data.right + 1
					})
				}

				var questions = this.data.examList[index];		//试卷题目集对象
				console.log(questions)
				var obj = questions.content[0];
				var arr = []
				var brr = []
				for (let i in obj) {
					arr.push(obj[i]); //属性
					brr.push(i);
				}
				this.setData({
					"examPaper": questions,
					"content": arr,
					"brr": brr,
					"aa": false,
					"Detail": false,
				});
				if (type == 'check') {
					this.setData({
						choiceIndex: '',
						userChoice: [],
					})
				}
			} else {
				if (type == 'check') {
					this.setData({
						userChoice: [],
					})
				}

				//如果错误显示详解，wrong+1
				this.setData({
					"wrong": this.data.wrong + 1,
					"Detail": true,
					"aa": false,
					'answerChoice': answer + ',' + choice,
				})
			}
		} else {
			this.setData({
				nextOk: false,
				submitOk: true,
			})

			if (choice == answer || Detail) {
				if (choice == answer) {
					this.setData({
						right: this.data.right + 1
					})
				}

				var questions = this.data.examList[index];		//试卷题目集对象
				console.log(questions)
				if (questions != undefined) {
					var obj = questions.content[0];
					var arr = []
					var brr = []
					for (let i in obj) {
						arr.push(obj[i]); //属性
						brr.push(i);
					}
					this.setData({
						"examPaper": questions,
						"content": arr,
						"brr": brr,
						"aa": false,
						"Detail": false,
						userChoice: [],
					});
					if (type == 'check') {
						this.setData({
							userChoice: [],
						})
					}
				}

			} else {
				//如果错误显示详解，wrong+1
				this.setData({
					"wrong": this.data.wrong + 1,
					"Detail": true,
					"aa": false,
				})
			}
		}

	},

	//结束答题
	overExam: function() {
		wx.confirm({
			title: '终止答题',
			content: '您是否想终止答题？',
			confirmButtonText: '是',
			cancelButtonText: '否',
			success: (result) => {
				var confirm = result.confirm;
				if (confirm) {
					//是返回上一层
					wx.navigateBack({
						delta: 1
					})
				} else {
					//否继续答题
					this.showPageMsg("tips", "可以继续答题!");
				}
			},
		});
	},

	//提交
	submit: function() {
		this.loadExamCheck();
	},

	closePop() {
		let that = this;
		that.setData({
			scorePop: false,
		})
	},

	loadExamCheck: function() {
		var examId = this.data.examId;
		var again = this.data.again;
		var newUrl = getApp().globalData.dangjianUrl + "/exam/examCheck";
		var params = {};
		var detailId = this.data.detailArr.join(',');
		var answer = this.data.choiceArr.join('#');
		params["examId"] = examId + "";
		params["detailId"] = detailId + "";
		params["answer"] = answer + "";
		params = JSON.stringify(params);
		this.httpGet(newUrl, params, "查询考试成绩结果接口调用失败").then(
			(respData) => {
				console.log(respData)
				var result = respData.data.result.code;
				if (1 == result) {
					var exam = respData.data.examResult;
					console.log(exam);
					//不是从 重新答题跳转的就 刷新父页面
					if (again == undefined) {
						var pages = getCurrentPages();
						var prevPage = pages[pages.length - 2];
						var examList = prevPage.data.examList;
						for (var i in examList) {
							if (examList[i].examId == examId) {
								examList[i].scoreNum = exam.score
							}
						}
						prevPage.loadExamList("0");
					}

					if (null != exam && undefined != exam) {
						this.setData({
							scorePop: true,
							"examCheck": exam,
							userChoice: [],
						});
					}
				} else {
          this.showPageMsg("alert", respData.data.result.description)
				}
			}
		);
	},


	//开始考试详情
	examinationPage(event) {
		var again = event.currentTarget.dataset.again;
		var examId = event.currentTarget.dataset.examid;
		var timeLimit = event.currentTarget.dataset.timelimit;
		wx.navigateTo({
			url: '../examination/examination?examId=' + examId + '&timeLimit=' + timeLimit + '&again=' + again
		})

	},
});
